<template>
	<view class="pb-150">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar title="检验判定依据" :autoBack="false" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder @leftClick="onLeftClick">
			<view class="u-nav-slot" slot="right">
				<view class="fs-32 colfff" @tap="goadd()">添加</view>
			</view>
		</u-navbar>
		<!-- 搜索 -->
		<!-- <view class="w-710 mgt">
			<u-search placeholder="请输入搜索内容" v-model="keyword" bgColor="#fff"></u-search>
		</view> -->
		<!-- 筛选 -->
		<view class="bgff br-20 pl-32 pr-32 w-710 mgt pt-20 pb-20">
			<!-- 监测年份 -->
			<view class="mb-20 rowsb rowsm">
				<view class="fs-28 col666">监测年份</view>
				<view class="rows rowsm">
					<u-input v-model="filterForm.startYear" placeholder="开始年份" type="number" border="none"
						class="w-150 mr-20"
						:customStyle="{ backgroundColor: '#f5f5f5', borderRadius: '8rpx', padding: '0 15rpx' }"></u-input>
					<view class="fs-28 col666 mr-20">至</view>
					<u-input v-model="filterForm.endYear" placeholder="结束年份" type="number" border="none" class="w-150"
						:customStyle="{ backgroundColor: '#f5f5f5', borderRadius: '8rpx', padding: '0 15rpx' }"></u-input>
					<u-icon name="calendar" size="20" color="#999" class="ml-20"></u-icon>
				</view>
			</view>

			<!-- 监测类别和级别 -->
			<view class="rows rowsm">
				<view class="mr-20 rows rowsm">
					<view class="fs-28 col666 mr-20">监测类别</view>
					<view class="rows rowsm" @click="showCategoryPicker = true">
						<view class="fs-28">{{ selectedCategoryLabel }}</view>
						<u-icon name="arrow-down" size="16" color="#999" class="ml-10"></u-icon>
					</view>
				</view>
				<view class="f-1 rows rowsm">
					<view class="fs-28 col666 mr-20">级别</view>
					<view class="rows rowsm" @click="showLevelPicker = true">
						<view class="fs-28">{{ selectedLevelLabel }}</view>
						<u-icon name="arrow-down" size="16" color="#999" class="ml-10"></u-icon>
					</view>
				</view>
				<!-- 操作按钮 -->
				<view class="rows rowsm">
					<view class="w-80 h-52 br-32 rowsc rowsm fs-28" style="border: 2rpx solid #ff6b35; color: #ff6b35;"
						@click="resetFilter">
						重置
					</view>
					<view class="w-80 h-52 br-32 rowsc rowsm fs-28 colfff ml-20" style="background-color: #ff6b35;"
						@click="applyFilter">
						查询
					</view>
				</view>
			</view>
		</view>
		<!-- 为空 -->
		<view class="rowsc rowsm" style="height: 80vh;" v-if="list.length === 0">
			<u-empty mode="data" icon="data"></u-empty>
		</view>
		<!-- 列表 -->
		<view class="w-710 mt-20 bgff pl-32 pr-32 br-20 mgt pt-32 pb-12" v-for="(item, index) in list" :key="index"
			@click="goDetail(item)">
			<view class="rowsb rowsm mb-20">
				<view class="rows rowsm	">
					<image src="/static/icon_rw.png" class="w-40 h-40 mr-20" mode="aspectFill"></image>
					<view class="fs-32 fw-b one_overflow">
						{{ item.title }}
					</view>
				</view>
				<view class="rows rowsm">
					<image src="/static/icon_b.png" class="w-32 h-32 mr-20" mode="aspectFill" @click.stop="goEdit(item)"
						v-if="item.status == 'draft'"></image>
					<image src="/static/icon_f.png" class="w-32 h-32 mr-20" mode="aspectFill"
						@click.stop="goCopy(item)"></image>
					<image src="/static/icon_s.png" class="w-32 h-32 mr-20" mode="aspectFill"
						@click.stop="goDelete(item)" v-if="item.status == 'draft'"></image>
				</view>
			</view>
			<view class="rowsl">
				<view class="fs-28 rows rowsm mb-20">
					<view class="col666 label ">年份</view>
					<view class="col666 ml-10 mr-10">:</view>
					<view class="fs-28 one_overflow">
						{{ item.year }}
					</view>
				</view>
				<view class="fs-28 rows rowsm mb-20">
					<view class="col666 label">录入人员</view>
					<view class="col666 ml-10 mr-10">:</view>
					<view class="fs-28 one_overflow">
						{{ item.people }}
					</view>
				</view>
				<view class="fs-28 rows rowsm mb-20">
					<view class="col666 label">录入部门</view>
					<view class="col666 ml-10 mr-10">:</view>
					<view class="fs-28 one_overflow">
						{{ item.department }}
					</view>
				</view>
				<view class="fs-28 rows rowsm mb-20">
					<view class="col666 label">录入时间</view>
					<view class="col666 ml-10 mr-10">:</view>
					<view class="fs-28 one_overflow">
						{{ item.time }}
					</view>
				</view>
				<view class="fs-28 rows rowsm mb-20">
					<view class="col666 label">状态</view>
					<view class="col666 ml-10 mr-10">:</view>
					<view class="fs-28 one_overflow">
						{{ item.status == 'draft' ? '草稿' : '已发布' }}
					</view>
				</view>
			</view>
		</view>
		<u-safe-bottom></u-safe-bottom>

		<!-- 监测类别选择器 -->
		<u-picker :show="showCategoryPicker" :columns="[categoryOptions]" @confirm="onCategoryConfirm"
			@cancel="showCategoryPicker = false" title="选择监测类别"></u-picker>

		<!-- 级别选择器 -->
		<u-picker :show="showLevelPicker" :columns="[levelOptions]" @confirm="onLevelConfirm"
			@cancel="showLevelPicker = false" title="选择级别"></u-picker>

		<!-- 复制选择弹框 -->
		<u-popup :show="showCopyDialog" mode="center" width="670rpx" @close="closeCopyDialog" :round="22">
			<view class="w-670 bgfff br-32 pl-42 pr-42 pt-32 pb-32">
				<view class="fs-40 fw-b mb-32 text-center">复制检验判定依据</view>

				<!-- 年份选择 -->
				<view class="mb-32">
					<view class="fs-28 col666 mb-20">
						年份 <text class="col-red">*</text>
					</view>
					<view class="rows rowsm" @click="showCopyYearPicker = true">
						<view class="fs-28 flex-1" :class="copyForm.year ? 'col333' : 'col999'">
							{{ copyForm.year || '请选择年份' }}
						</view>
						<u-icon name="calendar" size="20" color="#999"></u-icon>
					</view>
				</view>

				<!-- 检测类型选择 -->
				<view class="mb-32">
					<view class="fs-28 col666 mb-20">检测类型</view>
					<view class="rows rowsm" @click="showCopyTypePicker = true">
						<view class="fs-28 flex-1" :class="copyForm.detectionType ? 'col333' : 'col999'">
							{{ copyForm.detectionType || '请选择检测类型' }}
						</view>
						<u-icon name="arrow-down" size="16" color="#999"></u-icon>
					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="rows rowsm">
					<view class="w-120 h-52 br-32 rowsc rowsm fs-28 mr-20"
						style="border: 2rpx solid #0B993C; color: #0B993C;" @click="closeCopyDialog">
						取消
					</view>
					<view class="w-120 h-52 br-32 rowsc rowsm fs-28 colfff" style="background-color: #0B993C;"
						@click="confirmCopy">
						确定复制
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 复制年份选择器 -->
		<u-picker :show="showCopyYearPicker" :columns="[yearOptions]" @confirm="onCopyYearConfirm"
			@cancel="showCopyYearPicker = false" title="选择年份"></u-picker>

		<!-- 复制检测类型选择器 -->
		<u-picker :show="showCopyTypePicker" :columns="[typeOptions]" @confirm="onCopyTypeConfirm"
			@cancel="showCopyTypePicker = false" title="选择检测类型"></u-picker>
	</view>
</template>

<script>
import { getToken } from '@/utils/auth'
import { listProductStandard, delProductStandard, copyProductStandard, updateProductStandard } from '@/api/productStandard'
import request from '@/utils/request'
import navbarMixin from '@/common/navbarMixin'
export default {
	onReachBottom() {
		// 触底加载更多
		if (this.finished || this.loading) return
		this.pageNum += 1
		this.getList(true)
	},
	mixins: [navbarMixin],
	data() {
		return {
			keyword: '',
			list: [],
			id: '',
			// 分页
			pageNum: 1,
			pageSize: 10,
			total: 0,
			loading: false,
			finished: false,
			// 字典：检测类型 code->label
			detectionTypeMap: {},
			levelTypeMap: {},
			// 字典：检测类型 label->code
			labelToValueMap: {},
			// 字典：级别 label->code
			levelLabelToValueMap: {},
			detectionTypeDictType: 'product_monitor_type',
			// 筛选相关
			filterForm: {
				startYear: '',
				endYear: '',
				category: '',
				level: ''
			},
			showCategoryPicker: false,
			showLevelPicker: false,
			categoryOptions: ['全部'], // 初始为默认值，将从API动态加载
			levelOptions: ['全部'],
			// 复制弹框相关
			showCopyDialog: false,
			copyItem: null,
			copyForm: {
				year: '',
				detectionType: ''
			},
			showCopyYearPicker: false,
			showCopyTypePicker: false,
			yearOptions: [],
			typeOptions: []
		}
	},
	computed: {
		selectedCategoryLabel() {
			// 现在filterForm.category存储的是detectionType值，需要通过detectionTypeMap获取标签
			if (!this.filterForm.category) return '全部'
			return this.detectionTypeMap[this.filterForm.category] || '全部'
		},
		selectedLevelLabel() {
			// 现在filterForm.level存储的是值，需要通过levelTypeMap获取标签
			if (!this.filterForm.level) return '全部'
			return this.levelTypeMap[this.filterForm.level] || '全部'
		}
	},
	onLoad() {
		// 同时加载监测类别和级别字典
		Promise.all([
			this.loadDetectionDict(),
			this.loadLevelDict()
		]).then(() => {
			this.resetAndLoad()
		}).catch(() => {
			this.resetAndLoad()
		})

		// 初始化复制弹框的选项
		this.initCopyOptions()

		console.log('APP Token =', getToken())
	},
	methods: {
		// 重置并首次加载
		resetAndLoad() {
			this.pageNum = 1
			this.total = 0
			this.finished = false
			this.list = []
			this.getList(false)
		},
		// 获取列表，支持加载更多
		getList(isLoadMore = false) {
			if (this.loading || this.finished) return
			this.loading = true

			// 构建查询参数
			const params = {
				pageNum: this.pageNum,
				pageSize: this.pageSize,
				orderByColumn: 'input_time',
				isAsc: 'desc',
			}

			// 添加筛选条件
			if (this.keyword) {
				params.keyword = this.keyword
			}
			if (this.filterForm.startYear) {
				params.startYear = this.filterForm.startYear
			}
			if (this.filterForm.endYear) {
				params.endYear = this.filterForm.endYear
			}
			if (this.filterForm.category) {
				params.detectionType = this.filterForm.category
			}
			if (this.filterForm.level) {
				params.detectionLevel = this.filterForm.level
			}

			listProductStandard(params).then((res) => {
				const rows = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res?.data?.rows) ? res.data.rows : [])
				const total = typeof res?.total === 'number' ? res.total : (typeof res?.data?.total === 'number' ? res.data.total : 0)
				this.total = total
				const mapped = rows.map((row) => ({
					title: (this.detectionTypeMap[row.detectionType] || row.detectionType || '—'),
					year: row.year || '—',
					people: row.person || '—',
					department: row.department || '—',
					time: row.createTime || '—',
					id: row.id,
					detectionType: row.detectionType,// 保存原始detectionType用于复制
					status: row.status,
				}))
				this.list = isLoadMore ? this.list.concat(mapped) : mapped
				if (!rows.length || (this.total && this.list.length >= this.total) || rows.length < this.pageSize) {
					this.finished = true
				}
			}).catch(err => {
			}).finally(() => {
				this.loading = false
			})
		},
		async loadDetectionDict() {
			try {
				const res = await request({ url: `/system/dict/data/type/${this.detectionTypeDictType}`, method: 'get' })
				const rows = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : [])
				const map = {}
				const labelToValueMap = {} // 添加标签到值的映射
				const options = ['全部'] // uView Picker需要的是字符串数组，不是对象数组

				rows.forEach(d => {
					const label = d.dictLabel ?? d.label ?? d.name
					const value = d.dictValue ?? d.value ?? d.code
					if (value != null) {
						map[value] = label || value
						labelToValueMap[label || value] = value // 标签到值的映射
						options.push(label || value)
					}
				})

				this.detectionTypeMap = map
				this.labelToValueMap = labelToValueMap // 存储标签到值的映射
				this.categoryOptions = options
				// 更新复制弹框的检测类型选项
				this.typeOptions = options.filter(item => item !== '全部')
			} catch (e) {
				this.detectionTypeMap = {}
				this.labelToValueMap = {}
			}
		},
		async loadLevelDict() {
			try {
				const res = await request({ url: '/system/dict/data/type/syl_product_monitor_standard_level', method: 'get' })
				const rows = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : [])
				const options = ['全部'] // uView Picker需要的是字符串数组，不是对象数组

				rows.forEach(d => {
					const label = d.dictLabel ?? d.label ?? d.name
					const value = d.dictValue ?? d.value ?? d.code
					if (value != null) {
						options.push(label || value)
						// 建立级别标签到值的映射
						this.levelLabelToValueMap[label || value] = value
						// 建立值到标签的映射
						this.levelTypeMap[value] = label || value
					}
				})

				this.levelOptions = options
			} catch (e) {
			}
		},
		goDetail(item) {
			const id = item && item.id ? item.id : this.id
			uni.navigateTo({
				url: '/pages/workbench/01task/011detail?id=' + id
			})
		},
		goEdit(item) {
			const id = item && item.id ? item.id : this.id
			uni.navigateTo({
				url: '/pages/workbench/01task/011detail?id=' + id + '&mode=edit'
			})
		},
		goCopy(item) {
			const id = item && item.id ? item.id : this.id
			if (!id) {
				uni.showToast({ title: '未获取到ID', icon: 'none' })
				return
			}

			// 显示复制选择弹框
			this.showCopyDialog = true
			this.copyItem = item
		},
		goDelete(item) {
			const id = item && item.id ? item.id : this.id
			if (!id) {
				uni.showToast({ title: '未获取到ID', icon: 'none' })
				return
			}
			uni.showModal({
				title: '提示',
				content: '确定删除该检验判定依据吗？',
				success: (res) => {
					if (res.confirm) {
						delProductStandard(id).then(() => {
							uni.showToast({ title: '删除成功', icon: 'success' })
							this.resetAndLoad()
						}).catch(err => {
							console.error('删除失败:', err)
						})
					}
				}
			})
		},
		goadd() {
			uni.navigateTo({
				url: '/pages/workbench/01task/015add'
			})
		},
		gosearch() {
			uni.navigateTo({
				url: '/pages/workbench/01task/016search'
			})
		},
		onLeftClick() {
			// 返回工作台
			uni.redirectTo({
				url: '/pages/workbench/workbench'
			})
		},
		// 筛选相关方法
		onCategoryConfirm(e) {
			// uView Picker的confirm事件返回的是选中的值数组
			const selectedLabel = e.value[0]
			// 将选中的标签转换为对应的detectionType值
			const detectionType = selectedLabel === '全部' ? '' : (this.labelToValueMap[selectedLabel] || '')
			this.filterForm.category = detectionType
			this.showCategoryPicker = false
		},
		onLevelConfirm(e) {
			// uView Picker的confirm事件返回的是选中的值数组
			const selectedLabel = e.value[0]
			// 将选中的标签转换为对应的值
			const levelValue = selectedLabel === '全部' ? '' : (this.levelLabelToValueMap[selectedLabel] || '')
			console.log('级别选择:', { selectedLabel, levelValue, levelLabelToValueMap: this.levelLabelToValueMap })
			this.filterForm.level = levelValue
			this.showLevelPicker = false
		},
		resetFilter() {
			this.filterForm = {
				startYear: '',
				endYear: '',
				category: '',
				level: ''
			}
			this.showCategoryPicker = false
			this.showLevelPicker = false
			// 重置后重新加载数据
			this.resetAndLoad()
		},
		applyFilter() {
			// 验证年份范围
			if (this.filterForm.startYear && this.filterForm.endYear) {
				if (parseInt(this.filterForm.startYear) > parseInt(this.filterForm.endYear)) {
					uni.showToast({
						title: '开始年份不能大于结束年份',
						icon: 'none'
					})
					return
				}
			}

			// 关闭选择器
			this.showCategoryPicker = false
			this.showLevelPicker = false

			// 重新加载数据
			this.resetAndLoad()
		},
		// 初始化复制弹框选项
		initCopyOptions() {
			// 生成年份选项（当前年份前后5年）
			const currentYear = new Date().getFullYear()
			const yearOptions = []
			for (let i = currentYear - 5; i <= currentYear + 5; i++) {
				yearOptions.push(i.toString())
			}
			this.yearOptions = yearOptions

			// 检测类型选项从已有的categoryOptions中获取（去掉"全部"）
			this.typeOptions = this.categoryOptions.filter(item => item !== '全部')
		},
		// 复制弹框相关方法
		closeCopyDialog() {
			this.showCopyDialog = false
			this.copyItem = null
			this.copyForm = {
				year: '',
				detectionType: ''
			}
		},
		onCopyYearConfirm(e) {
			const selectedYear = e.value[0]
			this.copyForm.year = selectedYear
			this.showCopyYearPicker = false
		},
		onCopyTypeConfirm(e) {
			const selectedType = e.value[0]
			this.copyForm.detectionType = selectedType
			this.showCopyTypePicker = false
		},
		confirmCopy() {
			// 验证必填字段
			if (!this.copyForm.year) {
				uni.showToast({
					title: '请选择年份',
					icon: 'none'
				})
				return
			}

			// 构建复制参数
			const copyParams = {
				id: this.copyItem.id,
				year: this.copyForm.year,
				detectionType: this.copyForm.detectionType
			}

			// 执行复制
			copyProductStandard(copyParams).then(() => {
				uni.showToast({ title: '复制成功', icon: 'success' })
				this.closeCopyDialog()
				this.getList()
			}).catch(err => {
				console.error('复制失败:', err)
				uni.showToast({ title: '复制失败', icon: 'none' })
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 750rpx;
	z-index: 1;
}

.label {
	width: 120rpx;
	/* 固定宽度在 flex 布局下也不被压缩 */
	flex: 0 0 120rpx;
	text-align-last: justify;
}
</style>
